/* ---------------------------------------------------------------------------------------------
 *
 *            Capital Alliance Software Confidential Proprietary
 *            (c) Copyright CAS 201{x}, All Rights Reserved
 *                          www.pekall.com
 *
 * ----------------------------------------------------------------------------------------------
 */
package com.pekall.myDictionary.core;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;

import android.content.Context;

import com.pekall.myDictionary.screens.ExplainScreen.Word;

public class BaiduDictSource extends DictSource {

	private final static String prefixUrl = "http://dict.baidu.com/s?wd=%s";
	private final static String mSource = "Baidu.com";

	public BaiduDictSource(Context context) {
		super(context);
	}

	@Override
	public String getUrl(String[] code) {
		String query = code[0];
		try {
			String url = String.format(prefixUrl, URLEncoder.encode(query.toLowerCase(),
					"utf-8"));
			return url;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public Object parseContent(String content) {
		String enword_begin = "<div id=\"dict\">";
		int index = content.indexOf(enword_begin) + enword_begin.length();
		int lastindex = content
				.indexOf(
						"<script type=\"text/javascript\">window.pagetype = 1;</script>",
						index);
		content = content.substring(index, lastindex);
		content = content.replaceAll(" {2,}", " ");// 把字符串s中的多个空格替换为一个空格
		content = content.replaceAll("\r\n|\t|&nbsp;", "");// 去掉换行符号,制表符
		content = content.replaceAll("amp;", "");// 去掉空格
		content = content.replaceAll("<div class=\"lic\">", "");// 去掉空格
		
		
		enword_begin = "<span class=\"enword\">";
		index = content.indexOf(enword_begin) + enword_begin.length();
		lastindex = content.indexOf("</span>", index);
		String enword = content.substring(index, lastindex);

		enword_begin = "<span class=\"type\">";
		index = content.indexOf(enword_begin) + enword_begin.length();
		lastindex = content.indexOf("<script>", index);
		String pron = content.substring(index, lastindex);
 
		enword_begin = "<script>";
		index = content.indexOf(enword_begin) + enword_begin.length();
		lastindex = content.indexOf("</script>", index);
		String audio = content.substring(index, lastindex);
		audio = "http://dict.baidu.com/"
				+ audio.substring(audio.indexOf("=") + 2, audio
						.lastIndexOf("\""));

		enword_begin = "<div id=\"en\">";
		index = content.indexOf(enword_begin) + enword_begin.length();
 
		String example = content.substring(index);
 
		
		Word word = new Word();
		HashMap<String, String> exampleMap = new HashMap<String, String>();
		exampleMap.put("web", example);
		word.key = enword;
		word.source = mSource;
		word.pron = pron;
		word.audio = audio;
		return word;
	}

	@Override
	public String getSource() {
		return mSource;
	}

}
